<?php

namespace Biz\service\salesRebate;

use Biz\model\GoodsExtendInfo as mGoodsExtendInfo;
use Biz\model\salesRebate\SalesAccount as mSalesAccount;
use Biz\model\salesRebate\SalesCoupon as mSalesCoupon;
use Biz\model\salesRebate\SalesOrder as mSalesOrder;
use Biz\pockets\constInterface\SalesRebateConfig;
use Biz\service\salesRebate\SalesRebate as sSalesRebate;
use Doraemon\amqp\Queue;
use Doraemon\tools\HhzClient;
use Doraemon\tools\Log;

/**
 * @deprecated
 */
class SalesOrder
{

    /**
     * 下单，创建返佣客户消费记录
     */
    public static function createSalesOrder($orderGoodsList, $appType)
    {
        $orderGoodsArr = array_values($orderGoodsList);
        $couponIds = array_column($orderGoodsArr, 'coupon_id');
        $couponIds = array_filter($couponIds);
        $couponIds = array_unique($couponIds);
        if (in_array($appType, [HhzClient::APPTYPE_IOS, HhzClient::APPTYPE_ANDROID])) {
            //app 返佣
            $salesCouponsList = sSalesRebate::getRebateInfosByCouponIds($couponIds);
        } else {
            //节选返佣
            $salesCoupons = sSalesRebate::getCode($couponIds);
            $salesCouponsList = [];
            foreach ($salesCoupons as $key => $row) {
                if ($row['status'] == mSalesCoupon::STATUS_OPEN) {
                    $salesCouponsList[$row['coupon_id']] = $row;
                }
            }
        }
        Log::info('sales coupons#' . json_encode($salesCouponsList, JSON_UNESCAPED_UNICODE));
        $goodsIds = [];
        foreach ($orderGoodsList as $skuId => $skuInfo) {
            $goodsIds[] = $skuInfo['goods_id'];
        }
        $goodsExtendArr = mGoodsExtendInfo::select(['goods_id', 'ratio_ext'], ['goods_id' => $goodsIds]);
        $goodsAppRateArr = [];
        foreach ($goodsExtendArr as $row) {
            $ratioExt = $row['ratio_ext'];
            $ratioExt = json_decode($ratioExt, true);
            $goodsSaleRate = ($ratioExt && isset($ratioExt['app_sale']['ratio'])) ? $ratioExt['app_sale']['ratio'] : 0;
            $goodsAppRateArr[$row['goods_id']] = $goodsSaleRate;
        }
        try {
            $result = mSalesOrder::action(function () use ($orderGoodsList, $salesCouponsList, $goodsAppRateArr) {
                foreach ($orderGoodsList as $skuId => $skuInfo) {
                    $couponId = $skuInfo['coupon_id'];
                    if ($couponId && isset($salesCouponsList[$couponId])) {
                        $salesCouponInfo = $salesCouponsList[$couponId];
                        $goodsAppRate = isset($goodsAppRateArr[$skuInfo['goods_id']]) ? $goodsAppRateArr[$skuInfo['goods_id']] : 0;
                        if ($salesCouponInfo['type'] == mSalesAccount::TYPE_PERSONAL || $salesCouponInfo['type'] == mSalesAccount::TYPE_COMPANY) {
                            $rate = SalesRebateConfig::DEFAULT_RATE;//默认返佣比例
                        } else if ($salesCouponInfo['type'] == mSalesAccount::TYPE_APP) {
                            $userRate = $salesCouponInfo['rebate_pct'];
                            if ($goodsAppRate > 0 && $userRate > 0) {//商品返佣设置为0，用户返佣设置为0，则不计入返佣
                                $rate = round(($goodsAppRate * $userRate) / 100, 2);
                            } else {
                                Log::info('商品Id：' . $skuInfo['goods_id'] . '不计入返佣记录，app带货最大反应比例为：' . $goodsAppRate . '带货用户uid:' . $salesCouponInfo['uid'] . '返佣比例：' . $userRate . '#coupnId:' . $couponId . '#order_no:' . $skuInfo['order_no']);
                                continue;
                            }
                        }
                        $addData = [
                            'uid' => $salesCouponInfo['uid'],
                            'consumer_uid' => $skuInfo['uid'],
                            'type' => $salesCouponInfo['type'],
                            'coupon_id' => $couponId,
                            'order_no' => $skuInfo['order_no'],
                            'goods_id' => $skuInfo['goods_id'],
                            'sku_id' => $skuInfo['sku_id'],
                            'rate' => $rate,
                            'sale_amount' => $skuInfo['pay_amount'],
                            'status' => mSalesOrder::STATUS_NORMAL,
                        ];
                        try {
                            $result = mSalesOrder::addData($addData);
                            if (!$result) {
                                throw new \Exception(json_encode($addData, JSON_UNESCAPED_UNICODE));
                            }
                        } catch (\Exception $e) {
                            throw new \Exception($e->getMessage() . '#' . json_encode($addData, JSON_UNESCAPED_UNICODE), $e->getCode());
                        }
                    }
                }
                return true;
            });
            return $result;
        } catch (\Exception $e) {
            $msg = json_encode(['order_goods' => $orderGoodsList, 'msg' => $e->getMessage(), 'file' => $e->getFile(), 'line' => $e->getLine()], JSON_UNESCAPED_UNICODE);
            Log::debug('下单，创建返佣客户消费记录失败#' . $msg);
            Queue::insertQueue("queue/Wechatnotice/toTag", [
                "totag" => \Biz\pockets\constInterface\BizWechatTagConfig::TAG_BIZ_RD_SYSTEM,
                "content" => '下单，创建返佣客户消费记录失败#' . $msg
            ], Queue::QUEUE_BIZ);
            return false;
        }
    }

    /**
     * 关闭订单后，消费记录置为失效状态
     * 仅商城订单系统（取消订单，订单退款成功）使用
     * @param $orderNo
     * @param $operateType 1:退款。2:取消
     * @param $goodsId
     * @param $skuId
     * @param $refundRmb 退款商品款
     * @return bool
     * @throws \Exception
     */
    public static function afterCloseOrder($orderNo, $operateType, $goodsId = 0, $skuId = 0, $refundRmb = 0)
    {
        $result = true;
        if ($operateType == 1) {//退款成功
            $where = [
                'status' => mSalesOrder::STATUS_NORMAL,
                'order_no' => $orderNo,
                'goods_id' => $goodsId,
                'sku_id' => $skuId,
            ];
            $salesOrder = mSalesOrder::getOneByWhere('*', $where);
            if ($salesOrder) {
                //减去已退商品款金额
                $saleAmount = bcsub($salesOrder['sale_amount'], $refundRmb, 2);
                if ($saleAmount > 0) {
                    $result = mSalesOrder::updateData(['sale_amount' => $saleAmount], $where);
                    Log::info("订单:" . $orderNo . '.#goods_id:.' . $goodsId . '#sku_id:' . $skuId . '商品款部分退款：' . $refundRmb . '。返佣消费金额更改为：' . $saleAmount);
                } else {
                    $result = mSalesOrder::updateData(['status' => mSalesOrder::STATUS_INVALID], $where);
                    Log::info("订单:" . $orderNo . '.#goods_id:.' . $goodsId . '#sku_id:' . $skuId . '商品款已退完：' . $refundRmb . '。返佣消费记录置为失效状态');
                }
            } else {
                Log::info("订单:" . $orderNo . '.#goods_id:.' . $goodsId . '#sku_id:' . $skuId . '返佣消费记录未查询到。#sales_order:' . json_encode($salesOrder, JSON_UNESCAPED_UNICODE));
            }
        } else if ($operateType == 2) {//取消订单
            $where = [
                'status' => mSalesOrder::STATUS_NORMAL,
                'order_no' => $orderNo,
            ];
            $result = mSalesOrder::updateData(['status' => mSalesOrder::STATUS_INVALID], $where);
            Log::info("订单:" . $orderNo . '取消。返佣消费记录置为失效状态');
        } else {
            throw new \Exception('更改返佣消费记录状态，订单操作类型不正确');
        }
        return $result;
    }

    public static function admGetOrderList($params = [])
    {
        $list = [];
        $total = 0;
        return ['list' => $list, 'total' => $total];
    }

}
